// pages/talent-certificate/talent-certificate.js
var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var WxParse = require('../../wxParse/wxParse.js');
var base64 = require('../../utils/Base64.js');
var app = getApp();
var page = 1;
var inviteuid = '';

var hb_info = '';

var screen_w = 320;

var timer = '';
Page({

  /**
   * 页面的初始数据
   */
  data: {
  
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    var tc = app.get_tc();
    var titlename = tc == 1 ? '人才培訓 ' : '人才培训 ';
    wx.setNavigationBarTitle({
      title: titlename,
    });
    wx.showLoading({
      title: '加载中',
    })

    hb_info = '';

    var that = this;
    //获取绑定orgid信息
    app.GetUserInfo(util.orgid, function (res) {
      console.log("绑定机构信息：", res);
      // wx.setNavigationBarTitle({
      //   title: res.uname,
      // });
      that.setData({
        org_name: res.uname
      })
    });

    wx.getSystemInfo({
      success: function (res) {
        var isiPhone = (res.model.indexOf('iPhone') >= 0);
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          tc:tc,
          isIphone: isiPhone,
          isIphone_x: isIphone_x,
          screen_w: res.windowWidth,
          screen_h: res.windowHeight,
        });
      }
    })
    //读取登录用户信息
    app.LoginUserInfo(function (res) {
      console.log("登录用户信息：", res);
      if (res && res != -1) {
        that.setData({
          loginuid: res.uid,
          token: res.token
        });
        //设置用户信息
        app.GetUserInfo(res.uid, function (res) {
          var up = '';
          if (res.photo) {
            up = res.photo.split(',');
          }
          //更新数据
          that.setData({
            userInfo: res,
            userphotos: up
          })

        });
      }
    }, inviteuid);
    that.getGoodsClassly()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that=this
    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color
      })
      that.resetNavColor();
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },

  getGoodsClassly: function () {
    //读取商品分类数据
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "goodstype",
        "tc": that.data.tc
      },
      success: function (responseData) {
        console.log("商品分类数据：", responseData.data);
        var goodsType = responseData.data;
        if (goodsType.msg) {
          wx.hideLoading();
        } else {
          that.setData({
            goodsTypeArray: goodsType
          })
          that.loadTopicList();
          // for (var i = 0; i < goodsType.length; i++) {
          //   that.loadFenleiGoodsData(goodsType[i], i);
          // }
        }
      }
    });
  },

  loadTopicList: function(){
    var that = this;
    var index=12;
    var params = {
      "publickey": util.publiccode,
      "ac": "indexslideForTalent",
      "uid": util.orgid,
      "block": index,
      "tc": that.data.tc
    };
    util.api({
      data: params,
      success: function (responseData) {
        console.log(index + "-- swiper image:", responseData);
        var result = responseData.data;
        if (result && result.length > 0) {
            console.log(result);
            result.forEach(function (m, i) {
              var col = parseInt(m.col);
              col = col == 0 ? 1 : col;
              result[i].img_w = screen_w / col;
              console.log("贴图宽：" + m.img_w + "; col = " + col);
            });

            //课程分类列表（不包含咨询分类列表）
            var classList = [];
            for (var i = 0; i < that.data.goodsTypeArray.length; i++) {
              if (that.data.goodsTypeArray[i].goods_id == 579) {
                classList = that.data.goodsTypeArray[i].child;
              }
            }
            console.log("classList", classList);
            //课程分类列表（包含咨询分类列表）
            var classArr = [{ goods_id: '', title: '', subList: [] }];
            for (var i = 0; i < result.length; i++) {
              var exist = false;
              if (i == 0) {
                classArr[0].goods_id = result[0]['gtype'];
                classArr[0].subList.push(result[0]);
              }
              if (i > 0) {
                for (var j = 0; j < classArr.length; j++) {
                  if (classArr[j].goods_id == result[i]['gtype']) {
                    classArr[j].subList.push(result[i]);
                    exist = true;
                    break
                  }
                }
                if (!exist) {
                  if (result[i]['gtype'].length == 6) {
                    let classObj = { goods_id: '', title: '', subList: [] };
                    classObj.goods_id = result[i]['gtype'];
                    classObj.subList.push(result[i]);
                    console.log("classObj", classObj);
                    classArr.push(classObj);
                    console.log("classArr", classArr);
                  }
                }
              }
            }
            //赋值课程中文名
            for (var i = 0; i < classArr.length; i++) {
              for (var j = 0; j < classList.length; j++) {
                if (classArr[i].goods_id == classList[j].goods_id) {
                  classArr[i].title = classList[j].title;
                }
              }
              if (classArr[i].title == '') {
                classArr.splice(i, 1);
                i--
              }
            }
            classArr.sort(function (a, b) {
              return a.goods_id - b.goods_id
            });

            
            classArr.forEach(function(m,i){
              // if(m.goods_id=="355577"){
              //   that.setData({
              //     topicList:m.subList
              //   });
              // }
              m.subList.forEach(function (n,j) {
                n.message = app.parseHTMLText(n.message);
                console.log(n.message)

              })
            })
            that.setData({
              classArray: classArr
            });
            // that.data.topicList.forEach(function (m, i) {
            //   m.message = app.parseHTMLText(m.message);

            // })
            // that.setData({
            //   topicList: that.data.topicList
            // });
            
            that.loadClassList();
            that.loadClassCurrent(that.data.currentClass);
          
        }
        wx.hideLoading();
      }
    });

  },
  loadFenleiGoodsData: function (goodsTypeOb, index) {
    var that = this;
    var goodsId = goodsTypeOb.goods_id;
    var params = {
      publickey: util.publiccode,
      ac: "topiclist",
      topictype: '4',
      toporder: '1',
      tc: that.data.tc,
      orgid: util.orgid,
      gtype: goodsId,
      // zhiding: '1',
      page: 1,
      num: 10
    };
    console.log("商品参数：", params);
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("商品数据" + goodsId + ": ", result);
        if (result.msg) {
          goodsTypeOb.goodsArray = [];
          goodsTypeOb.noData = true;
        } else {
          var count = result.length;
          result.forEach(function (m, i) {
            result[i].count = count;
          });
          goodsTypeOb.goodsArray = result;
          goodsTypeOb.noData = false;
        }
        var goodsTypeArr = that.data.goodsTypeArray;
        goodsTypeArr[index] = goodsTypeOb;
        that.setData({
          goodsTypeArray: goodsTypeArr
        })
        wx.hideLoading();
      }
    });
  },


  resetNavColor: function () {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
    this.setData({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },


  swiperAction: function (e) {
    var data = e.currentTarget.dataset.info;
    app.saveFormId(e.detail.formId);
    console.log("swiper data:", data);
    if (data) {
      var go_type = data.type;
      var go_id = data.data;
      if (go_type == "topic") {//去详情页
        var url = "/pages/detail/detail?topicid=" + go_id;
        wx.navigateTo({ url: url })
      } else if (go_type == "url") {
        var url = go_id;
        if (url.indexOf('/pages/') >= 0) {
          wx.navigateTo({ url: url })
        } else if (url.indexOf('showToast') >= 0) {
          this.pindanAction();
        } else {
          // app.dialog('未定义跳转' + url, 'success');
        }
      } else {
        // app.dialog('未定义跳转：' + go_type + '--' + go_id, 'success');
      }
    }
  },

  // if(util.orgid == 15671) {
  //   title = '求职，企业招聘，人才培训……壹号人才欢迎您';
  // }
  //页面分享
  onShareAppMessage: function () {
    var that = this;
    var inviteuid = that.data.loginuid ? that.data.loginuid : '';
    console.log("分享id" + inviteuid);
    return {
      title: '求职，企业招聘，人才培训……壹号人才欢迎您',
      path: '/pages/talent-certificate/talent-certificate?&inviteuid=' + inviteuid
    };
  },


  loadClassList: function () {
    var that = this;
    if (that.data.currentClass == '') {
      that.data.currentClass = that.data.classArray[0].goods_id;
      console.log("currentClass=====that.data.classArray[0].goods_id=================》》》", that.data.classArray[0].goods_id);
    }
    this.setData({
      classArray: this.data.classArray,
      currentClass: this.data.currentClass,
      currcata: 0
    })
  },

  loadClassCurrent: function (option) {
    console.log("currentClass======================》》》", option);
    console.log("classArray======================》》》", this.data.classArray);
    var classid = option;
    var zixunfenlei = [];
    for (var i = 0; i < this.data.classArray.length; i++) {
      if (classid == this.data.classArray[i].goods_id) {
        zixunfenlei = this.data.classArray[i].subList;
      }
    }
    console.log("zixunfenlei======================》》》", zixunfenlei);
    this.setData({
      classArray: this.data.classArray,
      currentClass: classid,
      zixunfenlei: zixunfenlei,
    })
  },
  // 滑块切换标签样式
  switchTab: function (e) {
    this.setData({
      currcata: e.detail.current
    });
    e.currentTarget.dataset.cataid = this.data.classArray[e.detail.current].goods_id;
    e.currentTarget.dataset.index = e.detail.current;

    this.changeClass(e);
    this.checkCor();
  },
  changeClass: function (e) {
    console.log(e.currentTarget.dataset.classid);
    var classid = e.currentTarget.dataset.classid;
    var cataindex = e.currentTarget.dataset.index;
    var zixunfenlei = [];
    for (var i = 0; i < this.data.classArray.length; i++) {
      if (classid == this.data.classArray[i].goods_id) {
        zixunfenlei = this.data.classArray[i].subList;
      }
    }
    this.setData({
      currentClass: classid,
      zixunfenlei: zixunfenlei,
      currcata: cataindex,
    })

    console.log(classid, cataindex);
  },

  //判断当前滚动超过一屏时，设置tab标题滚动条。
  checkCor: function () {
    this.setData({
      scrollLeft: 300 * parseInt(this.data.currcata / 3)
    })
  },
})